package com.example.teesystem.common.valid;

import com.example.teesystem.common.cache.CourseCache;
import com.example.teesystem.common.cache.KnowledgeCache;
import com.example.teesystem.common.cache.UserCache;
import lombok.RequiredArgsConstructor;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

@RequiredArgsConstructor
public class CustomValidIdValidator implements ConstraintValidator<ValidId, Integer> {
    private int minValue;
    private boolean ifUserId;
    private boolean ifCourseId;
    private boolean ifKnowledgeId;
    
    /**
     * 初始化方法
     * @param constraintAnnotation 给定约束声明的注解实例
     */
    @Override
    public void initialize(ValidId constraintAnnotation) {
        this.minValue = constraintAnnotation.minValue();
        this.ifUserId = constraintAnnotation.ifUserId();
        this.ifCourseId = constraintAnnotation.ifCourseId();
        this.ifKnowledgeId = constraintAnnotation.ifKnowledgeId();
    }
    
    /**
     * 校验
     * @param value 待校验的值
     * @param context 评估约束的上下文
     * @return
     */
    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        if(value == null) {
            return false;
        }
        if(this.ifUserId) {
            return UserCache.userMap.containsKey(value);
        } else if(this.ifCourseId) {
            return CourseCache.courseMap.containsKey(value);
        } else if(this.ifKnowledgeId) {
            return KnowledgeCache.knowledgeMap.containsKey(value);
        } else {
            return value >= this.minValue;
        }
    }
}
